package com.tistory.admin.common;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import com.tistory.admin.common.log.OmpLogger;

public class CryptoUtil {

	private static final String SP_ASSOC_KEY = "6b0cc48e477f066b7ef353a4f9e8b756";

	private String toHex(byte hash[]) {
		StringBuffer buf = new StringBuffer(hash.length * 2);

		for (int i = 0; i < hash.length; i++) {
			int intVal = hash[i] & 0xff;
			if (intVal < 0x10) {
				// append a zero before a one digit hex
				// number to make it two digits.
				buf.append("0");
			}
			buf.append(Integer.toHexString(intVal));
		}
		return buf.toString();
	}

	/**
	 * SP_AUTH_KEY 작성시 호출해야할 Mac 생성 API
	 * 
	 */
	public String generateMacSignature(String key, String message) throws Exception {
		SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(), "HmacSHA1");

		Mac mac = Mac.getInstance("HmacSHA1");
		mac.init(skeySpec);

		byte[] result = mac.doFinal(message.getBytes());

		return toHex(result);
	}

	public String getSpAuthKey() {
		String timeStamp = Long.toString(System.currentTimeMillis());
		String signature = "sp_id=OMP10000|time=" + timeStamp + "|domain=www.omp.com";

		CryptoUtil crypto = new CryptoUtil();

		String spAuthKey = "";
		try {
			spAuthKey = crypto.generateMacSignature(SP_ASSOC_KEY, signature.toString()) + "|" + timeStamp;
		} catch (Exception e) {
			OmpLogger.error(e.getMessage(), e);
		}

		return spAuthKey;
	}

	public static void main(String[] args) throws Exception {

		String spId = "OMP10000";
		String time = Long.toString(System.currentTimeMillis());
		String domain = "www.omp.com";

		StringBuffer sb = new StringBuffer();
		sb.append("sp_id=");
		sb.append(spId);
		sb.append("|");
		sb.append("time=");
		sb.append(time);
		sb.append("|");
		sb.append("domain=");
		sb.append(domain);

		CryptoUtil crypto = new CryptoUtil();
		String spAuthKey = null;
		try {
			spAuthKey = crypto.generateMacSignature(SP_ASSOC_KEY, sb.toString());
		} catch (Exception e) {
			OmpLogger.error(e.getMessage(), e);
		}

		System.out.println("result = " + spAuthKey);
	}
}
